<?php

namespace app\modules\api\controllers;

use app\controllers\BaseController;
use app\models\cacheModel\AdminRoleModel as AdminRoleCacheModel;
use app\models\CommonModel;
use app\models\tableModel\AdminRoleModel as AdminRoleDBModel;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * [更新缓存]操作控制器
 */
class CacheController extends BaseController
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [ // 请求方式
                'class' => VerbFilter::className(),
                'actions' => [
                    'admin-menu' => ['GET', 'POST'],
                ],
            ],
            'access' => [ // 是否游客可以访问
                'class' => AccessControl::className(),
                'rules' => [
                    [ // 必须登陆才能访问
                        'actions' => [
                            'admin-menu',
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [ // 无需登陆即可访问
                        'actions' => [],
                        'allow' => false,
                        'roles' => ['?']
                    ]
                ]
            ]
        ];
    }

    /**
     * 更新后台角色菜单缓存
     *  ` 每次获取20个角色，更新其菜单缓存 `
     * @return mixed
     */
    public function actionAdminMenu()
    {

        // 第几页
        $page = $this->get('page', 'integer', 1);
        // 每页最大角色数
        $pageSize = 20;

        // ********** 增加可以一次刷新规定角色编号线下的缓存 **********
        $idList = $this->post('idList');
        // 传输角色编号，角色编号为空
        if (!empty($idList) && count($idList) <= 0) {

            return $this->jsonFail('刷新角色菜单：请选择一个角色条目', 400, [
                'error_hint' => '未传输任何编号',
                'error_code' => 403
            ]);
        }
        // 传输角色编号，角色编号个数大于每页展示最大个数
        if (!empty($idList) && count($idList) <= 0) {

            return $this->jsonFail('刷新角色菜单：角色每次最多选择' . $pageSize . '条', 400, [
                'error_hint' => '角色编号传输了' . count($idList) . '条，最多传输' . $pageSize . '条',
                'error_code' => 400
            ]);
        }

        $idList = [2];
        // 条件
        $where = ['AND'];
        if (!empty($idList)) {
            $where[] = ['IN', 'id', is_array($idList) ? $idList : explode(',', $idList)];
        }

        $dbModel = AdminRoleDBModel::loadModel()->loadWhere($where);
        // 角色列表
        $roleList = $dbModel->getList($page, $pageSize, 'id, name');
        // 角色总数
        $roleCount = $dbModel->getCount();

        foreach ($roleList as $k => $v) {

            // ******************* 1、清除[数据库]中角色菜单信息 *******************
            $roleDb = AdminRoleDBModel::loadModel($v);
            if (!$roleDb) {
                return $this->jsonFail('刷新角色菜单：角色【' . $v['name'] . '】不存在', 404, [
                    'id' => $v['id'],
                    'errorHint' => '角色未找到',
                    'errorColumn' => 'id'
                ]);
            }
            // 更新下角色菜单
            if (!$roleDb->updateMenu()) {
                $error = CommonModel::getModelError($roleDb->errors);
                return $this->jsonFail('刷新角色菜单：角色【' . $v['name'] . '】数据更新失败',
                    400, [
                        'id' => $v['id'],
                        'errorHint' => $error['msg'],
                        'errorColumn' => $error['column']
                    ]);
            }

            // ******************* 2、清除[缓存]中角色菜单信息 *******************
            $roleCache = AdminRoleCacheModel::loadModel($v);
            if (!$roleCache) {
                $roleCache = AdminRoleCacheModel::loadModel();
                $roleCache->setAttributes($roleDb->getAttributes());
            }

            // 赋值菜单
            $roleCache->setAttribute('menu', $roleDb->getAttribute('menu'));
            // 更新下角色菜单
            if (!$roleCache->saveData()) {
                $error = CommonModel::getModelError($roleCache->errors);
                return $this->jsonFail('刷新角色菜单：角色【' . $v['name'] . '】缓存更新失败',
                    400, [
                        'id' => $v['id'],
                        'errorHint' => $error['msg'],
                        'errorColumn' => $error['column']
                    ]);
            }
        }

        // 进度
        $allPage = ceil($roleCount / $pageSize);
        // 下一页是否还有数据 - 默认否
        $nextPageHave = false;
        if ($allPage == $page) {

            $progress = '全部更新完毕';
        } else {

            $progress = '共' . $allPage . '页/第' . $page . '页';
            $nextPageHave = true;
        }

        return $this->jsonSuccess('刷新角色菜单：' . $progress, [
            'nextPageHave' => $nextPageHave
        ]);
    }
}
